const {loadModule} = window['vue3-sfc-loader'];
import store from "../store/index.js";
import tool from "../utils/tool/index.js";

const modules = [{path: '/src/views/index/index.vue'}, {path: '/src/views/document/index.vue'},];

// 系统路由
const staticRouteList = [{
    name: "layout",
    path: "/",
    component: () => Vue.defineAsyncComponent(() => loadModule('/src/layout/index.vue', options)),
    redirect: 'index',
    children: [],
    meta: {
        title: "框架", type: "MENU",
    },
},];

const router = VueRouter.createRouter({
    history: VueRouter.createWebHashHistory(), routes: staticRouteList
})

// 设置标题
document.title = store.getters.getSiteInfo.title;

// 判断是否已加载过动态 / 静态路由
let isGetRouter = false;

router.beforeEach(async (to, from, next) => {
    // 开始加载条
    Pace.start();
    // 动态标题
    document.title = to.meta.title;
    if (flatAsyncRoutes(staticRouteList).findIndex(r => r.path === to.path) >= 0) {
        // 系统路由直接放行
        next();
        return false;
    } else if (to.meta?.type === 'LINK' && to.meta?.url) {
        // 处理超链接
        tool.openLink(to.meta?.url);
    } else {
        // 加载动态 / 静态路由
        if (!isGetRouter) {
            // 所有动态路由
            let asideMenuList = store.getters.getAsideMenuList;
            let menuList = store.getters.getNavigationMenuList;
            let thirdList = store.getters.getIconMenuList;
            let footerLinkList = store.getters.getNormalMenuList;
            let friendLinkList = store.getters.getFriendMenuList;
            // 合并路由
            let dynamicRouterList = [...asideMenuList, ...menuList, ...thirdList, ...footerLinkList, ...friendLinkList];
            // 填充
            dynamicRouterList = filterAsyncRouter(dynamicRouterList);
            // 一维化
            dynamicRouterList = flatAsyncRoutes(dynamicRouterList);
            // 加入 layout
            dynamicRouterList.forEach(item => router.addRoute("layout", item));
            if (to.matched.length === 0) {
                router.push(to.fullPath);
            }
            isGetRouter = true;
        }
        next();
    }
});

router.afterEach((to, from) => {
    // 结束加载条
    Pace.stop();
});

// 路由扁平化
function flatAsyncRoutes(routes, breadcrumb = []) {
    let res = []
    routes.forEach(route => {
        const tmp = {...route}
        if (tmp.children) {
            let childrenBreadcrumb = [...breadcrumb]
            childrenBreadcrumb.push(route)
            let tmpRoute = {...route}
            tmpRoute.meta.breadcrumb = childrenBreadcrumb
            delete tmpRoute.children
            res.push(tmpRoute)
            let childrenRoutes = flatAsyncRoutes(tmp.children, childrenBreadcrumb)
            childrenRoutes.map(item => {
                res.push(item)
            })
        } else {
            let tmpBreadcrumb = [...breadcrumb]
            tmpBreadcrumb.push(tmp)
            tmp.meta.breadcrumb = tmpBreadcrumb
            res.push(tmp)
        }
    })
    return res
}

// 转换
function filterAsyncRouter(dynamicRouterList) {
    const accessedRouters = [];
    if (dynamicRouterList && dynamicRouterList.length > 0) {
        dynamicRouterList.forEach(item => {
            item.meta = item.meta ? item.meta : {};
            // 处理外部链接特殊路由
            if (item.meta.type === 'LINK') {
                item.meta.url = item.component;
            }
            // MAP 转路由对象
            let route = {
                path: item.path,
                name: item.name,
                meta: item.meta,
                redirect: item.redirect,
                children: item.children ? filterAsyncRouter(item.children) : null,
                component: Vue.defineAsyncComponent(() => loadModule(loadComponent(item), options)),
            }
            accessedRouters.push(route);
        })
    }
    return accessedRouters;
}

function loadComponent(route) {
    if (route.meta.type === 'MENU' && route.component) {
        for (let i = 0; i < modules.length; i++) {
            const dir = modules[i].path.split('views/')[1].split('.vue')[0];
            if (dir === route.component || dir === route.component + '/index') {
                return modules[i].path;
            }
        }
    }
    // 返回 404
    return "/src/views/error/404/index.vue";
}

export default router;